package com.ctrip.coverage.service.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bstek.dorado.hibernate.HibernateDao;
import com.ctrip.coverage.model.dto.BuildPublishDto;
import com.ctrip.coverage.model.dto.TfsFolderDto;
import com.ctrip.coverage.model.entity.SonarDataEntity;
import com.ctrip.coverage.model.entity.TfsFolderEntity;
import com.ctrip.coverage.orm.dao.BaseDaoI;
import com.ctrip.coverage.orm.ibaits.dao.SonarDataDaoI;
import com.ctrip.coverage.service.CodeBuild;
import com.ctrip.coverage.service.CodeLibrary;
import com.ctrip.coverage.service.HttpClientService;
import com.ctrip.coverage.service.SonarService;
import com.ctrip.coverage.service.SvnCheckOutService;
import com.ctrip.coverage.utils.config.CodelibraryConfig;
import com.ctrip.coverage.utils.config.RCConfig;
import com.ctrip.coverage.utils.enums.CodeLibraryType;
import com.ctrip.coverage.utils.enums.SonarExecuteResult;
import com.ctrip.coverage.utils.enums.TfsCollection;

@Component
public class SonarServiceImpl extends HibernateDao implements SonarService {
	@Autowired
	RCConfig config;
	@Autowired
	SonarDataDaoI<SonarDataEntity> sonarDataDao;
	@Autowired
	HttpClientService httpClientService;
	@Autowired
	SvnCheckOutService svnCheckOutService;
	@Autowired
	CodelibraryConfig codelibraryConfig;
	@Autowired
	CodeLibrary codeLibrary;
	@Autowired
	CodeBuild codeBuild;
	@Autowired
	BaseDaoI<SonarDataEntity> sonarDataEntityDao;
	Process proc;
	String str;
	Runtime rt = Runtime.getRuntime();
	BufferedReader bufferedReader;
	String localPath;
	Integer isSonarSuc = SonarExecuteResult.FAI;

	/**
	 * c#扫描服务
	 */
	public synchronized void scanCsharpProject(TfsFolderEntity tfsFolderEntity, String version) {

		//切换规则
		String setDefaultUrl = config.getSonarUrl() + "/api/profiles/set_as_default";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		String ruleName = sonarDataDao.getSonarRuleNameById(tfsFolderEntity.getScanRule());
		params.add(new BasicNameValuePair("language", "cs"));
		params.add(new BasicNameValuePair("name", ruleName));
		httpClientService.requestPost(setDefaultUrl, params);
		if (null == version) {
			version = "999999";
		}
		BuildPublishDto buildPublishDto = new BuildPublishDto();
		buildPublishDto.setServerPath(tfsFolderEntity.getServerPath());
		buildPublishDto.setProjectName(tfsFolderEntity.getProjectName());
		if (tfsFolderEntity.getCodeLibraryType().equals(CodeLibraryType.TFS)) {
			localPath = tfsFolderEntity.getServerPath().replace("$", codelibraryConfig.getTfsMappingPath() + "\\" + TfsCollection.getName(tfsFolderEntity.getCollection()));
			localPath = localPath.replace("/", "\\");
			buildPublishDto.setTfsCollection(tfsFolderEntity.getCollection());
			buildPublishDto.setLocalPath(localPath);
			codeLibrary.tfsGetCommon();
			codeLibrary.tfsInit(buildPublishDto);
			codeLibrary.tfsGet(buildPublishDto);
		} else {
			localPath = codelibraryConfig.getGitMappingPath() + "\\" + tfsFolderEntity.getProjectPath();
			buildPublishDto.setLocalPath(localPath);
			codeLibrary.gitGet(buildPublishDto);
		}

		try {
			String buildLog = codeBuild.csharpDevenvBuild(buildPublishDto);
			StringBuffer sb = new StringBuffer();
			StringBuffer sonarLog = new StringBuffer();
			sb.append("sonar.projectKey=" + tfsFolderEntity.getId() + tfsFolderEntity.getName() + "\r\n");
			sb.append("sonar.projectName=" + tfsFolderEntity.getName() + "\r\n");
			sb.append("sonar.projectVersion=" + version + "\r\n");
			sb.append("sonar.sourceEncoding=gbk\r\n");
			sb.append("sonar.sources=.\r\n");
			sb.append("sonar.language=cs\r\n");
			sb.append("sonar.visualstudio.enable=true\r\n");
			if (null != tfsFolderEntity.getSkippedProjectPattern()) {
				sb.append("sonar.visualstudio.skippedProjectPattern=" + tfsFolderEntity.getSkippedProjectPattern() + "\r\n");
			}
			File sonarFile = new File(localPath + "/sonar-project.properties");
			if (!sonarFile.exists()) {
				sonarFile.createNewFile();
			}
			FileWriter fw = new FileWriter(sonarFile.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(sb.toString());
			bw.close();

			proc = rt.exec("cmd.exe /c sonar-runner", null, new File(localPath));

			bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			while ((str = bufferedReader.readLine()) != null) {
				sonarLog.append(str + "\r\n");
				if (str.contains("EXECUTION SUCCESS")) {
					isSonarSuc = SonarExecuteResult.SUC;
				}

			}
			proc.waitFor();
			sonarFile.delete();
			TfsFolderDto tfsFolderDto = new TfsFolderDto();
			tfsFolderDto.setId(tfsFolderEntity.getId());
			tfsFolderDto.setIdName(tfsFolderEntity.getId() + tfsFolderEntity.getName());
			tfsFolderDto.setName(tfsFolderEntity.getName());
			tfsFolderDto.setVersion(version);
			SonarDataEntity sonarDataEntity = sonarDataDao.findSnap(tfsFolderDto);
			Map<String, Float> sonarDatMap = sonarDataDao.findSonarData(sonarDataEntity.getNewestSnapId());
			BeanUtils.populate(sonarDataEntity, sonarDatMap);
			sonarDataEntity.setSonar_log(buildLog + "\r\n" + sonarLog.toString());
			sonarDataEntity.setResult(isSonarSuc);
			sonarDataEntity.setTfsFolder(tfsFolderEntity);
			sonarDataEntityDao.save(sonarDataEntity);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * java扫描服务
	 */
	public synchronized void scanJavaProject(TfsFolderEntity tfsFolderEntity, String version) {
		//切换规则
		String setDefaultUrl = config.getSonarUrl() + "/api/profiles/set_as_default";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		String ruleName = sonarDataDao.getSonarRuleNameById(tfsFolderEntity.getScanRule());
		params.add(new BasicNameValuePair("language", "java"));
		params.add(new BasicNameValuePair("name", ruleName));
		httpClientService.requestPost(setDefaultUrl, params);
		//获取代码
		svnCheckOutService.svnCheckOut(tfsFolderEntity.getServerPath(), codelibraryConfig.getSvnMappingPath() + tfsFolderEntity.getProjectName());
		//执行扫描
		if (version == null) {
			version = "999999";
		}
		StringBuffer sb = new StringBuffer();
		sb.append("sonar.projectKey=" + tfsFolderEntity.getId() + tfsFolderEntity.getName() + "\r\n");
		sb.append("sonar.projectName=" + tfsFolderEntity.getName() + "\r\n");
		sb.append("sonar.projectVersion=" + version + "\r\n");
		sb.append("sonar.sourceEncoding=utf-8\r\n");
		sb.append("sonar.sources= src\r\n");
		sb.append("sonar.language=java\r\n");
		try {
			File sonarFile = new File("D:/svndownload/" + tfsFolderEntity.getProjectName() + "/sonar-project.properties");
			if (!sonarFile.exists()) {
				sonarFile.createNewFile();
			}
			FileWriter fw = new FileWriter(sonarFile.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(sb.toString());
			bw.close();

			proc = rt.exec("cmd.exe /c sonar-runner", null, new File(codelibraryConfig.getSvnMappingPath() + tfsFolderEntity.getProjectName()));
			bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			while ((str = bufferedReader.readLine()) != null) {
				System.out.println(str);
			}
			proc.waitFor();
		} catch (Exception e) {
		}
	}

	public void saveSonarData() {

	}
}
